package controller

import (
	"cloud-storage/global"
	"cloud-storage/model/mysql"
	"cloud-storage/utils/response"
	"cloud-storage/utils/upload"
	"github.com/gin-gonic/gin"
	"github.com/lifei6671/gocaptcha"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"strings"
)

// ShareFile 创建分享文件
func ShareFile(c *gin.Context) {
	phone := global.GetPhone(c)
	user, err := mysql.GetUserInfo(phone)
	if err != nil {
		zap.L().Error("mysql.GetUserInfo() failed err:", zap.Error(err))
		response.ResponseError(c, response.CodeSelectOperationFail)
		return
	}
	fId := c.Query("id")
	url := c.Query("url")

	//获取文件
	code := gocaptcha.RandText(4)
	fileId, _ := strconv.Atoi(fId)

	hash := mysql.CreateShare(code, user.UserName, fileId)
	response.ResponseSuccess(c, gin.H{
		"url":  url + "?f=" + hash,
		"code": code,
	})
}

// SharePass 分享文件页面
func SharePass(c *gin.Context) {
	f := c.Query("f")

	//获取分享信息
	shareInfo := mysql.GetShareInfo(f)
	//获取文件信息
	file, err := mysql.GetFileInfo(strconv.Itoa(shareInfo.FileId))
	if err != nil {
		zap.L().Error("mysql.GetFileInfo() failed err:", zap.Error(err))
		response.ResponseError(c, response.CodeSelectOperationFail)
		return
	}
	response.ResponseSuccess(c, gin.H{
		"id":       shareInfo.FileId,
		"username": shareInfo.Username,
		"fileType": file.Type,
		"filename": file.FileName + file.Postfix,
		"hash":     shareInfo.Hash,
	})
}

// DownloadShareFile 下载分享文件
func DownloadShareFile(c *gin.Context) {
	fileId := c.Query("id")
	code := c.Query("code")
	hash := c.Query("hash")

	fileInfo, err := mysql.GetFileInfo(fileId)
	if err != nil {
		zap.L().Error("mysql.GetFileInfo() failed err:", zap.Error(err))
		response.ResponseError(c, response.CodeSelectOperationFail)
		return
	}

	//校验提取码
	if ok := mysql.VerifyShareCode(fileId, strings.ToLower(code)); !ok {
		c.Redirect(http.StatusMovedPermanently, "/file/sharePass?f="+hash)
		return
	}

	//从oss获取文件
	fileData, err := upload.DownloadOss(fileInfo.FileHash, fileInfo.Postfix)
	if err != nil {
		zap.L().Error("upload.DownloadOss() failed err:", zap.Error(err))
		response.ResponseError(c, response.CodeOperationFail)
		return
	}
	//下载次数+1
	err = mysql.DownloadNumAdd(fileId)
	if err != nil {
		zap.L().Error("mysql.DownloadNumAdd() failed err:", zap.Error(err))
		response.ResponseError(c, response.CodeOperationFail)
		return
	}

	c.Header("Content-disposition", "attachment;filename=\""+fileInfo.FileName+fileInfo.Postfix+"\"")
	c.Data(http.StatusOK, "application/octect-stream", fileData)
}
